package com.xiangyang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiangyang.entity.LoginUser;
import com.xiangyang.entity.User;
import com.xiangyang.entity.vo.UserDetailInfo;
import com.xiangyang.mapper.IPermsMapper;
import com.xiangyang.mapper.IRoleMapper;
import com.xiangyang.mapper.IUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


import java.util.List;
import java.util.Objects;


@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired

    private IUserMapper userMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private IPermsMapper menuMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private IRoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException {
        if (phone == null || phone.isEmpty())
            throw new InternalAuthenticationServiceException("用户名为空");
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUserPhone, phone);
        User user = userMapper.selectOne(lambdaQueryWrapper);
        if (Objects.isNull(user))
            throw new UsernameNotFoundException("用户不存在");
        //从数据库中查询权限
        List<String> list = menuMapper.getPermsByRoleId(user.getUserId());
        //将UserDetails所需的信息封装到UserInfo中
        UserDetailInfo userDetailInfo = new UserDetailInfo(user.getUserId(),user.getUserName(),user.getUserPassword(), user.getUserPhone(),user.getUserState(),roleMapper.getRoleNameByPhone(phone), list);
        //封装成UserDetails对象返回
        return new LoginUser(userDetailInfo);
    }

}
